/**
 * @fileOverview Custom code related to workflow
 * @author Wouter Bos
 * @since 1.0 - 2010-11-30
 * @version 1.0 - 2010-11-30
 */




/**
 * @namespace Workflow namespace
 */
var workflow = {}

/**
 * @namespace Form related stuff
 */
workflow.form = {}

workflow.form.radioButtonCtrl = (function() {
	function setupLabel() {
		jQuery('span.radioButton input').each(function() {
			var input = jQuery(this)
			input.parent().removeClass('radioOn');
			if (input.is(':checked') == true) {
				input.parent().addClass('radioOn');
			}
		});
	};

/* START PUBLIC */
	return {
		SetupLabel: function() {
		    jQuery('span.radioButton').each( function() {
			    jQuery(this).click(function() {
				    setupLabel();
			    });
			    jQuery(this).has(':checked').addClass('radioOn');
			})
		}
	}
	/* END PUBLIC */
})();

workflow.form.checkboxCtrl = (function() {
	function setupLabel() {
		jQuery('span.checkBoxLabel input').each(function() {
			var input = jQuery(this)
			input.parent().removeClass('checkBoxOn');
			if (input.is(':checked') == true) {
				input.parent().addClass('checkBoxOn');
			}
		});
	};

/* START PUBLIC */
	return {
		SetupLabel: function() {
		    jQuery('span.checkBoxLabel').each( function() {
			    jQuery(this).click(function() {
				    setupLabel();
			    });
			    jQuery(this).has(':checked').addClass('checkBoxOn');
			})
		}
	}
	/* END PUBLIC */
})();

/**
 * @namespace Creates skin for select form elements
 *
 * @requires jQuery
 */
workflow.form.select = (function() {
    /* START PUBLIC */
	return {
		/**
		 * Initializes the skin
		 * @param {String} selector jQuery selector that selects the SELECT-element
		 * @requires jQuery
		 * @example
		 * workflow.form.select.Init("select.js_styledDropdown");
		 */
		Init: function(selector) {
		    jQuery(selector).each( function() {
		        var materials = jQuery(this);
		        if (materials[0].tagName.toLowerCase() != "select") {
		            //if (console) {
		            //    console.log('Element is not of the type SELECT. Continuing...')
		            //}
		        } else {
	                var classes = jQuery(this).attr("class").split(' ');
	                var width = classes[classes.length-1]; 

		            jQuery(materials).addClass("init");
		            var matOptions = materials[0].options;
	                var selIndex = materials[0].selectedIndex;
	                if(selIndex == -1) return;
		            var list = "";
	                list += "<li class='selected'>"+matOptions[selIndex].innerHTML+"</li>";
            		
		            for(var i=0; i < matOptions.length; i++) {
		                var item = matOptions[i];
		                var active = (i == selIndex) ? "active highlight" : "";
	                    list += "<li class='option "+active+"'>"+item.innerHTML+"</li>";
	                }
	                
	                jQuery(this).after("<div class='styledDropdownContainer'><ul class='styledDropdown js_styledDropdown "+width+"'>"+ list +"</ul></div>");
	                
	                // IE6 hover fix for styling of hovering over non A-elements
	                jQuery(this).next('div').find('ul').click( function(e){
                        jQuery("ul.js_styledDropdown").not(this).removeClass("hover").parent().removeClass("hover");
                        jQuery(this).toggleClass("hover").parent().toggleClass("hover");
                        e.stopPropagation();
                    }).find('li').hover(
                        function(){
                            if(jQuery(this).hasClass('option')){
                                jQuery(this).siblings('.option').removeClass('highlight');
                                jQuery(this).addClass('highlight');
                            }
                        },
                        function(){
                            jQuery(this).removeClass('highlight').siblings().removeClass('highlight');
                            jQuery(this).parent().find('.active').addClass('highlight');
                        }
                    );
                    
                    // Hide open dropdowns when clicked outside the dropdown
                    jQuery("html").click( function(){
                        jQuery(".js_styledDropdown, .styledDropdownContainer").removeClass("hover");
                    });
        	        
	                jQuery(this).next('div').find('ul li.option').click( function(){
	                    jQuery(this).siblings().removeClass("active");
	                    jQuery(this).addClass("active");
	                    var index = jQuery(this).index()-1; // -1 because there is a dummy li item which takes index[0]
	                    materials[0].selectedIndex = index;
	                    materials[0].options[index].selected = true;
	                    jQuery(materials[0]).change();
	                    jQuery(this).siblings(".selected").text(jQuery(this).text());
	                });
	                
	                jQuery("div.filterOptions").scroll( function(){
	                    setTimeout( function(){
	                        jQuery('div.styledDropdownContainer').css({
	                            'margin-left':'1px'
	                        });            
                        }, 1); 
	                    setTimeout( function(){
	                        jQuery('div.styledDropdownContainer').css({
	                            'margin-left':'0'
	                        });	             
                        }, 2);
	                });
                }
		    });
		}
	}
	/* END PUBLIC */
})();





/**
 * @namespace Creates accordion. Adds accordion widget to a definition list (dl)
 *
 * @requires jQuery
 */
workflow.Accordion = (function() {
	/* START PUBLIC */
	return {
		/**
		 * Adds accordion widget to a definition list (dl)
		 * @param {String} selector jQuery selector that selects the dl element
		 * @requires jQuery
		 * @example
		 * workflow.Accordion.Init("dl.tag_informatieaccordeon")
		 */
		Init: function(selector) {
			// Set list
			jQuery(selector + " dt").addClass("a");
			jQuery(selector + " dd").hide();
			
			// Set click event
			jQuery(selector + " dt").not(".empty").click(function() {
				jQuery(this).parent().find("> dt").removeClass("active");
				jQuery(this).addClass("active");
				if (jQuery(this).next("dd").is(":hidden")) {
					jQuery(this).parent().find("> dd:visible").slideUp(400);
					jQuery(this).next("dd").slideDown(600);
				} else {
					jQuery(this).parent().find("> dd:visible").slideUp(400);
					jQuery(this).parent().find("> dt").removeClass("active");
				}
			})
		}
	}
	/* END PUBLIC */
})();





/**
 * @namespace Adds events to the filter panel
 *
 * @requires jQuery
 */
workflow.filter = (function() {
	/* START PUBLIC */
	return {
		/**
		 * Adds events to the filter panel
		 * @requires jQuery
		 * @example
		 * workflow.filter.Init()
		 */
		Init: function(selector) {
			jQuery('input.js_eraseFilter').click(function() {
				jQuery(':checkbox').attr('checked', false)
				jQuery('span.radioButton').removeClass("radioOn");
			})
			jQuery('input.js_cancel').click(function() {
				jQuery(':checkbox').attr('checked', false)
				jQuery('span.radioButton').removeClass("radioOn");
				top.jQuery('#FilterPanel').hide()
				top.jQuery('#TabContent1').show()
			})
		}
	}
	/* END PUBLIC */
})();



/**
 * @namespace Reloads parent window if filter form has been submitted
 *
 * @requires jQuery
 */
workflow.postfilter =(function() {
    jQuery('#ListFilterFrame').contents().find("span.js_loaded").data('set', true);
    var interval = setInterval(function() {
        if (jQuery('#ListFilterFrame').contents().find("span.js_loaded").size() > 0 && jQuery('#ListFilterFrame').contents().find("span.js_loaded").data('set') != true) {
            document.location = document.location
            clearInterval(interval);
        }
    }, 100)
});



/**
 * @namespace Creates accordion
 *
 * @requires jQuery
 */
workflow.accordion2 = (function() {
	return {
		/**
		 * Adds accordion widget to a definition list (dl)
		 * @param {String} selector jQuery selector that selects the dl element
		 * @requires jQuery
		 * @example
		 * workflow.accordion2.Init("dl.tag_informatieaccordeon")
		 */
		Init: function(selector) {
			var root = jQuery(selector);

			root.addClass("js_accordion")
			root.find("dd:gt(0)").hide()
			//jQuery(this).addClass('dt').first().addClass('active')
			
			//alert(window.top.document.getElementById('AlertDetailsFrame'))
			
			var containerHeight = jQuery(window.top.document.getElementById('AlertDetailsFrame')).innerHeight();
			var listHeight = 0;
			root.find('> dt').each(function() {
				listHeight += jQuery(this).innerHeight(true)
			})
			var maxDdSpace = 160;
			
			root.find("dt").click(function() {
				var isIE6 = false;
				if (jQuery('body.ie6').size() > 0) {
					isIE6 = true;
				}
				var dt = jQuery(this);
				dt.parent().find('dt').removeClass('active')
				dt.addClass('active')
				if (dt.next("dd").is(":hidden")) {
					dt.siblings("dd").slideUp(400);
					if (isIE6) {
						dt.next("dd").css(
							{
								'height': '0px',
								'display': 'block'
							}
						)
						dt.next("dd").animate(
							{
								'overflow': 'scroll',
								'height': maxDdSpace + 'px'
							},
							{
								duration: 600
							}
						);
					} else {
						dt.next("dd").css(
							{
								'max-height': '0px',
								'display': 'block'
							}
						)
						dt.next("dd").animate(
							{
								'max-height': maxDdSpace + 'px'
							},
							{
								duration: 600
							}
						);
					}
				}
			})
		}
	}
})();






/**
 * @namespace Creates an accordion especially for the new alerts dialogue
 *
 * @requires jQuery
 */
workflow.newAlertAccordion = (function() {
	var editMode = false
	if (document.location.href.indexOf('?alertId') > 0) {
		editMode = true
	}



	return {
		/**
		 * Adds accordion widget to a defenition list (dl)
		 * @param {String} selector jQuery selector that selects the dl element
		 * @requires jQuery
		 * @example
		 * workflow.accordion2.Init("dl.tag_informatieaccordeon")
		 */
		Init: function(selector) {
			//detailBox
			jQuery(selector).each(function() {
				var root = jQuery(this);
				
				root.addClass("js_accordion")
				root.find("dd:gt(0)").hide()
				root.find('dt').first().addClass('active')
				if (editMode == true) {
					root.find('dt').addClass('accessible')
				} else {
					root.find('dt').first().addClass('accessible')
				}
				
				//var containerHeight = root.closest('div.detailBox').innerHeight();
				//var listHeight = 0;
				//root.find('dt').each(function() {
				//	listHeight += jQuery(this).outerHeight(true)
				//})
				//var maxDdSpace = containerHeight - listHeight;

				root.find("dt").click(function() {
					var clickedDt = jQuery(this)
					if (clickedDt.hasClass('accessible') == true) {
						clickedDt.parent().find('dt').removeClass('active')
						clickedDt.addClass('active')
						if (clickedDt.next("dd").is(":hidden")) {
							clickedDt.siblings("dd").slideUp(400);
							clickedDt.next("dd").slideDown(600, function() {
								if (clickedDt.is('.tag_map')) {
									workflow.newAlert.OpenAlertMap()
								}
								if (clickedDt.is('.js_step3')) {
									setTimeout( function(){
										jQuery('div.styledDropdownContainer').css({
											'position':'static'
										});            
									}, 610); 
									setTimeout( function(){
										jQuery('div.styledDropdownContainer').css({
											'position':'relative'
										});	             
									}, 620);
								}
							});
						}
					}
				})

			});
		}
	}
})();






/**
 * @namespace Sets events for new alert wizard
 *
 * @requires jQuery
 */
workflow.newAlert = (function() {
	var root
	var editMode = false
	if (document.location.href.indexOf('?alertId') > 0) {
		editMode = true
	}

	function setMunicipalitySelect() {
		jQuery('ul.tag_municipalities li').css('cursor', 'pointer')
		jQuery('ul.tag_municipalities li :checked').closest('li').addClass('active')
		jQuery('ul.tag_municipalities li').click( function(event) {
			jQuery(root).find('.tag_map').addClass('reset')
			event.stopPropagation()
			jQuery('ul.tag_municipalities li').removeClass('active')
			jQuery(this).addClass('active')
			jQuery(this).closest('dd').prev('dt').find('span.selected').text(jQuery(this).text())
			jQuery('*.tag_newAlertSave').attr('disabled', true).addClass("disabled");
			jQuery(root).find('dt:lt(2)').addClass('accessible')
			jQuery(root).find('dt:gt(1)').removeClass('accessible')
			jQuery(root).find('dd:visible').next('dt').click()
		 })
	}
	
	function clearMap() {
		jQuery('div.tag_markerInput input.rcbInput').val('')
		jQuery('div.tag_areaInput input.tag_areaDesciption').val('')
		jQuery('input.rcbInput').val('')
		jQuery('dt.js_step3').removeClass('accessible')
		jQuery('*.tag_newAlertSave').attr('disabled', true).addClass("disabled");
		newAlertMap.ClearMap()
	}
	
	function openAlertMap() {
		if (jQuery('ul.tag_municipalities li.active').size() > 0) {
			var lng
			var lat
			var showSpecialMarker
			if (jQuery(root).find('.tag_map').hasClass('reset')) {
				lng = parseFloat(jQuery('ul.tag_municipalities li.active input.tag_lng').val())
				lat = parseFloat(jQuery('ul.tag_municipalities li.active input.tag_lat').val())
				showSpecialMarker = false;
			} else {
				var marker = jQuery('input.tag_markerLatLng').val().split(";")
				lat = parseFloat(marker[0])
				lng = parseFloat(marker[1])
				showSpecialMarker = true;
			}
			if (!newAlertMap) {
				newAlertMap = new Estate.GoogleMaps(
					{
						mapId: 'Map',
						startLocation: {
							lng: lng,
							lat: lat,
							zoom: parseInt(jQuery('ul.tag_municipalities li.active input.tag_zoom').val()),
							text: '',
							showMarker: false,
							showSpecialMarker: showSpecialMarker
						}
					},
					"newAlertMap"
				)
				newAlertMap.Init('newAlert')
				
				jQuery('#ClearMap').click(clearMap)
			} else {
				if (jQuery(root).find('.tag_map').hasClass('reset')) {
					clearMap()
					newAlertMap.ReInit
					(
						{
							lng: parseFloat(jQuery('ul.tag_municipalities li.active input.tag_lng').val()),
							lat: parseFloat(jQuery('ul.tag_municipalities li.active input.tag_lat').val()),
							zoom: parseInt(jQuery('ul.tag_municipalities li.active input.tag_zoom').val()),
							showMarker: false
						}
					)
				}
			}
			jQuery(root).find('.tag_map').removeClass('reset')
		}
	}
	
	function setMarkerSelection() {
		jQuery('div.tag_areaInput').hide()
		
		jQuery('div.tag_markerType :radio').change( function() {
			jQuery('div.tag_markerInput input.rcbInput').val("")
			jQuery('div.tag_areaInput input.tag_areaDesciption').val("")
			jQuery(root).find('dt:eq(2)').removeClass('accessible')
			jQuery('*.tag_newAlertSave').attr('disabled', true).addClass("disabled");
			
			newAlertMap.ClearMap()
			if (jQuery(this).val() == "rdArea") {
				newAlertMap.SetNewAlertConfig( {addAlertType: 'area'} )
				if (jQuery('div.tag_markerInput:visible').size() > 0) {
					jQuery('div.tag_markerInput').fadeOut(200, function() {
						jQuery('div.tag_areaInput').fadeIn(200, function() {
							if (jQuery.browser.msie == true) {
								this.style.removeAttribute("filter");
							}
						})
					} )
				}
				jQuery('input.tag_areaPoints').val('')
			} else {
				newAlertMap.SetNewAlertConfig( {addAlertType: 'point'} )
				if (jQuery('div.tag_areaInput:visible').size() > 0) {
					jQuery('div.tag_areaInput').fadeOut(200, function() {
						jQuery('div.tag_markerInput').fadeIn(200, function() {
							if (jQuery.browser.msie == true) {
								this.style.removeAttribute("filter");
							}
						})
					})
				}
				jQuery('input.tag_markerLatLng').val('')
			}
		})
	}
	
	function setStreetSearch() {
		jQuery('div.tag_markerInput :submit').removeAttr('onclick')
		jQuery('div.tag_markerInput :submit').bind('click keyup', function(event) {
			event.preventDefault()
			event.stopPropagation()
			newAlertMap.SetNewAlertByAddress(jQuery('div.tag_markerInput input.rcbInput').val())
			jQuery(root).find('span.tag_gotoStep3').text('')
			jQuery(root).find('span.tag_gotoStep3Area').text('')
		})
	}
	
	function setNavButtons() {
		jQuery(root).find('input.tag_gotoStep3').click( function() {
			if (isMarkerSelected() || isAreaSelected()) {
				jQuery(root).find('dt:lt(3)').addClass('accessible')
				jQuery(root).find('dt:eq(2)').click()
				jQuery('.tag_newAlertSave').attr('disabled', false).removeClass("disabled");
				gotoStep3()
			} else {
				jQuery(root).find('span.tag_gotoStep3').text('Plaats een marker op de kaart.')
				jQuery(root).find('span.tag_gotoStep3Area').text('Selecteer het gebied op de kaart en geef het een naam.')
			}
		})
		
		jQuery(root).find('dt:eq(2)').click( function() {
			gotoStep3()
		})
	}
	
	function isAreaSelected() {
		if (jQuery('div.tag_areaInput input.tag_areaDesciption').val() != "" && jQuery('input.tag_areaPoints').val() != "" && jQuery('input.tag_markerLatLng').val() != "") {
			return true;
		}
		return false
	}
	
	function isMarkerSelected() {
		var inputMarker = jQuery('div.tag_markerInput input.rcbInput')
		if (jQuery(inputMarker).val() != "") {
			return true;
		}
		return false
	}
	
	function gotoStep3() {
		var inputMarker = jQuery('div.tag_markerInput input.rcbInput')
		var inputArea = jQuery('div.tag_areaInput input.tag_areaDesciption')
		var locationText

		if (jQuery(inputArea).val() != "") {
			locationText = jQuery(inputArea).val()
		} else {
			locationText = jQuery(inputMarker).val()
		}
		jQuery(root).find('dt:eq(1)').find('span.selected').text(locationText)
		jQuery(root).find('span.tag_gotoStep3').text('')
		jQuery(root).find('span.tag_gotoStep3Area').text('')
	}
	
	return {
		/**
		 * @example
		 * workflow.newAlert.Set('dl.tag_newAlert')
		 */
		Set: function(selector) {
			root = jQuery(selector)
			
			if (editMode == false) {
				jQuery('*.tag_newAlertSave').attr('disabled', true).addClass("disabled");
			}
			workflow.newAlertAccordion.Init(root)
			
			setMunicipalitySelect()
			setMarkerSelection()
			setStreetSearch()
			setNavButtons()
		},
		
		/**
		 * @example
		 * workflow.newAlert.OpenAlertMap()
		 */
		OpenAlertMap: function() {
			openAlertMap()
		}
	}
})();






workflow.alertDetails = (function() {
/* START PUBLIC */
	return {
		ShowHideDetails: function(inputSelector, detailsBoxSelector) {
			var iframe = self.frameElement;
			var originalWidth = jQuery(iframe).innerWidth()
			
			if (jQuery(detailsBoxSelector).find('> *').size() > 0) {
				jQuery('div.tag_detailExtendedBox').hide()
				jQuery(iframe).animate(
					{width: "100%"},
					1000,
					"easeInOutCubic",
					function() {
						jQuery('div.tag_detailExtendedBox').show()
					}
				)
			} else {
				if (jQuery(iframe).innerWidth() > 400) {
					jQuery(iframe).animate( {width: "358px"}, 1000, "easeInOutCubic")
				} else if (jQuery(iframe).innerWidth() < 100) {
					jQuery(iframe).closest('div.tag_mapContainer').removeClass('mapContainerSummary')
				} else {
					jQuery(iframe).css('width', '358px')
				}
			}
		}
	}
	/* END PUBLIC */
})();





/**
 * @namespace Opens a page in an iframe that is placed in a HTML popup
 */
workflow.openFrame = (function() {
	function getUrl(urlType, id, rootPath) {
		switch(urlType) {
			case "dialogApprove":
				return rootPath+ "Alerts/Newalerts/partapprovepage.aspx?alertId="+ id
				break;
			case "dialogDeny":
				return rootPath+ "Alerts/Newalerts/rejectpage.aspx?alertId="+ id
				break;
			case "dialogExecuted":
				return rootPath+ "Alerts/InProgress/executed.aspx?alertId="+ id
				break;
			case "dialogExecuted2":
				return rootPath+ "Alerts/Executed/executed.aspx?alertId="+ id + "&part=true"
				break;
            case "dialogExecuted3":
                return rootPath + "Alerts/Executed/executed.aspx?alertId=" + id+"&save=no"
                break;
            case "dialogExecuted4":
                return rootPath + "Alerts/Executed/executed.aspx?alertId=" + id
                break;
			case "dialogDecline":
			    return rootPath + "Alerts/Executed/declinepage.aspx?alertId=" + id
				break;
			default:
				return ""
		}
	}

	function placePopupCode(html) {
		if (!document.getElementById('PopupFrameWindow')) {
			var popupHTML = '';
			popupHTML += '<div id="PopupFrameWindow" class="divPopupWindow divFrameWindow"><div class="innerDivPopupWindow">';
			popupHTML += '    <div class="close"></div>';
			popupHTML += '    <div class="popupContent" id="PopupContent"></div>';
			popupHTML += '</div>';
			popupHTML += '<div class="popupContentFooter"></div>';
			popupHTML += '</div>';
			popupHTML += '<div id="PopupFrameBackground" class="divPopupBackground divFrameBackground"></div>';
			jQuery('body').append(popupHTML);
		} else {
			jQuery('#PopupFrameWindow div.popupContent').html('');
		}

		if (typeof (html) == 'string') {
			jQuery('#PopupFrameWindow div.popupContent').html(html);
		}
	}
	
	/* START PUBLIC */
	return {
		/**
		 * Opens a page in an iframe that is placed in a HTML popup
		 *
		 * @param {String} urlType URL to open page
		 * @param {String} id adds a class to the iframe
		 * @param {String} rootPath path of the url to be loaded
		 * @example
		 * workflow.openFrame.Open('http://www.google.com', '/MunicipalityName/')
		 */
		Open: function(urlType, id, rootPath) {
			var url = getUrl(urlType, id, rootPath)
			
			if (url != null) {
				placePopupCode("<iframe src='"+ url +"' class='"+ id +"' frameborder='0' allowtransparency='true'></iframe>")
				
				var popup = new Estate.Popup({
					animationSpeed: 250,
					windowSelector: "#PopupFrameWindow",
					backgroundSelector: "#PopupFrameBackground"
				});
				popup.Open();
			} else {
				throw new Error('Cannot find an url for the iframe')
			}
		},
		
		/**
		 * Closes a popup from within the iframe. If needed it will also reload the page
		 *
		 * @param {Boolean|String} doReload If true, it will reload the parent document,
		 *	if it's a string, it will handle it as an URL.
		 * @example
		 * workflow.openFrame.Close(true)
		 * workflow.openFrame.Close('/MunicipalityName/Alerts/NewAlerts.aspx')
		 */
		Close: function(doReload) {
			if (jQuery(top.document.getElementById('PopupFrameWindow')).find('div.close').size() > 0) {
				jQuery(top.document.getElementById('PopupFrameWindow')).find('div.close').click()
			}
			if (typeof(doReload) != "undefined") {
				if (doReload == true) {
					top.document.location.reload()
				} else if (typeof(doReload) == "string") {
					top.document.location = '/MunicipalityName/Alerts/NewAlerts.aspx'
				}
			}
		}
	}
	/* END PUBLIC */
})();






/**
 * @namespace Adds extra functionality to the alert page:
 * <ul>
 *	<li>- Paging</li>
 *	<li>- Action column events</li>
 *	<li>- Remove the head of the table and place it before the table</li>
 * </ul>
 *
 * @requires jQuery
 */
workflow.alertList = (function() {
	var config = {
		root: null,
		rootSelector: '',
		rowSelector: '> table > tbody > tr',
		pageSize: 10,
		maxPageButtons: 4,
		pagerSelector: 'listPager',
		headerSelector: 'listHeader',
		rootPath: ''
	}
	
	// Set up paging controls
	function init(el) {
		var itemsLength = jQuery(el).find(config.rowSelector).size()
		var pageButtonsLength = Math.ceil(itemsLength / config.pageSize)
		
		setButtons(el)
		
		// Move header outside the table
		var thead = jQuery(el).find('thead').detach()
		if (jQuery(el).find('tbody td:first:only-child').size() == 0) {
			// Only shows header if table has contents
			jQuery(el).before('<div class="'+ config.headerSelector +' '+ jQuery(el).attr('class') +'"><table><thead>'+ jQuery(thead).html() +'</thead></table></div>')
			setHeader(el)
		}

		if (pageButtonsLength > 1) { // There are enough items to implement paging
			// Create pager HTML
			var pageButtonsHTML = ""
			var start = 0
			var stop = 0
			for (var i = 0; i < pageButtonsLength; i++) {
				start = (config.pageSize*i) + 1
				stop = start + config.pageSize - 1
				pageButtonsHTML += "<li><a href='javascript:void(0)'>"+ start +" - "+ stop +"</a></li>"
			}
			pageButtonsHTML = "<ul>" + pageButtonsHTML +"</ul>"
			pageButtonsHTML = "<a href='javascript:void(0)'>minder</a>" + pageButtonsHTML + "<a href='javascript:void(0)'>meer</a>"
			pageButtonsHTML = "<div class='" + config.pagerSelector + " tag_" + config.pagerSelector + "'>" + pageButtonsHTML + "</div>"
			jQuery(el).after(pageButtonsHTML)
			var listPager = jQuery(el).next('div.tag_'+ config.pagerSelector)
			
			showRelevantButtons(listPager, 0)
			
			// Set events
			jQuery(listPager).find('a').first().click( function() { // 'Less' button
				less_click(this)
			})
			jQuery(listPager).find('a').last().click( function() { // 'More' button
				more_click(this)
			})
			jQuery(listPager).find('ul a').click( function() { // Paging buttons
				paging_click(this)
			})
		}
	}
	
	// Group buttons in the table and add show/hide event to it
	function setButtons(el) {
		var hasButtons
		if (jQuery(el).find('tbody').has(':button, :submit').size() > 0) {
			hasButtons = true
		} else {
			hasButtons = false
		}
		
		jQuery(el).find('tbody tr').each( function(index) {
			var firstTd = jQuery(this).find('td:first')
			if (hasButtons) {
				jQuery(firstTd).addClass('first')
				jQuery(firstTd).append('<div class="setState tag_setState"></div>')
				showHideButtons(firstTd)
				var firstDiv = jQuery(this).find('td:first div.tag_setState')
				jQuery(firstDiv).hide()
				jQuery(this).find(':button, :submit').each( function(index2) {
					var td = jQuery(this).closest('td')
					jQuery(this).detach().appendTo(firstDiv)
					jQuery(td).closest('td').hide()
				})
				//jQuery(firstDiv).prepend('<input type="button" value="hide" class="hide" />')
				
				jQuery(this).addClass(jQuery(firstTd).find('div.tag_itemStatus').text())
				jQuery(this).addClass(jQuery(firstTd).find('div.tag_itemExpired').text()) // TODO: test this Item expired line
				
				setButtonEvents(firstDiv)
				
				if (index == 1) {
					var hideColumnsCount = jQuery(this).find(':button, :submit').size()
					jQuery(el).find('thead > tr > *:lt('+ hideColumnsCount +')').hide()
					jQuery(el).find('thead > tr > *:first-child').show()
				}
			} else {
			    if (jQuery(firstTd).closest('table').hasClass('showStatus')) {
				    jQuery(this).addClass(jQuery(firstTd).find('div.tag_itemStatus').text())
				    jQuery(this).addClass(jQuery(firstTd).find('div.tag_itemExpired').text()) // TODO: test this Item expired line
				    jQuery(firstTd).addClass("first")
				} else {
				    jQuery(firstTd).hide()
				    jQuery(firstTd).closest('table').find('thead th:first').hide()
				}
			}
		})
	}
	
	function setButtonEvents(buttonsHolder) {
		jQuery(buttonsHolder).find('.partApprove').click( function(event) {
			event.preventDefault()
			//event.stopPropagation()
			workflow.openFrame.Open('dialogApprove', jQuery(this).parent().find('.approve').val(), config.rootPath)
		})
		jQuery(buttonsHolder).find('.deny').click( function(event) {
			event.preventDefault()
			//event.stopPropagation()
			workflow.openFrame.Open('dialogDeny', jQuery(this).parent().find('.approve').val(), config.rootPath)
		})
		jQuery(buttonsHolder).find('.decline').click( function(event) {
			event.preventDefault()
			//event.stopPropagation()
			workflow.openFrame.Open('dialogDecline', jQuery(this).parent().find('.approve').val(), config.rootPath)
        })
        jQuery(buttonsHolder).find('.partAccept').click(function(event) {
            event.preventDefault()
            //event.stopPropagation()
            workflow.openFrame.Open('dialogExecuted2', jQuery(this).parent().find('.approve').val(), config.rootPath)
        })
        jQuery(buttonsHolder).find('.accept').click(function(event) {
            event.preventDefault()
            //event.stopPropagation()
            workflow.openFrame.Open('dialogExecuted4', jQuery(this).parent().find('.accept').val(), config.rootPath)
        })
	}
	
	// Add show/hide events to buttons in list
	function showHideButtons(el) {
		jQuery(el).click( function(event) {
			jQuery(this).closest('tbody').find('div.tag_setState:visible').clearQueue()
			jQuery(this).closest('tbody').find('div.tag_setState:visible').fadeOut(500, "easeInOutCubic")
			var div = jQuery(this).find('div.tag_setState')
			if (jQuery(div).is(':animated') == false) {
				if (jQuery(div).is(':visible') == true) {
					jQuery(div).fadeOut(500, "easeInOutCubic")
				} else {
					jQuery(div).fadeIn(500, "easeInOutCubic")
				}
			}
			event.stopPropagation()
		})
		
		jQuery(el).mouseleave( function(event) {
			var div = jQuery(this).find('div.tag_setState')
			jQuery(div).delay(1000).fadeOut(500, "easeInOutCubic")
		})
	}
	
	// Set widths in table header
	function setHeader(el) {
		var listHeader = jQuery(el).prev()
		jQuery(el).find('tr:first > *').each( function(index) {
			var paddingLeft = Estate.StringTools.RemoveMeasurement(jQuery(this).css('padding-left'))
			if (jQuery(this).is(':visible') == true) {
				jQuery(listHeader).find('th:eq('+ index +')').css('width', jQuery(this).innerWidth() - (paddingLeft * 2) +'px')
			} else {
				jQuery(listHeader).find('th:eq('+ index +')').hide()
			}
		});
		var stdWidth = jQuery(el).innerWidth();
		var tableWidth = jQuery(el).find('table.rgMasterTable').innerWidth();
		var headerMargin = stdWidth - tableWidth;
		jQuery(listHeader).css('padding-right',headerMargin+'px');
	}

	// Event 'Less' button
	function less_click(el) {
		showRelevantButtons(jQuery(el).closest('div.tag_'+ config.pagerSelector), -1)
	}

	// Event 'More' button
	function more_click(el) {
		showRelevantButtons(jQuery(el).closest('div.tag_'+ config.pagerSelector), 1)
	}
	
	// Event paging buttons
	function paging_click(el) {
		var root = jQuery(el).closest('div.tag_'+ config.pagerSelector).prev()
		var selectedItem = jQuery(root).find(config.rowSelector).eq( jQuery(el).closest('li').index() * config.pageSize )
		var newScrollTop = jQuery(selectedItem).position().top - jQuery(root).position().top
		jQuery(root).animate({ scrollTop: "+="+ newScrollTop +"px" }, 1000, "easeInOutCubic")
	}
	
	// Manages the visibility of the paging buttons
	function showRelevantButtons(listPager, arg_moveIndex) {
		var maxPageButtons = config.maxPageButtons
		var moveIndex
		
		if (arg_moveIndex == 0) {
			maxPageButtons++
			moveIndex = 0
		} else if (arg_moveIndex == 1) {
			moveIndex = jQuery(listPager).find('li:visible').last().index() + 1
			if ((moveIndex + maxPageButtons + 2) >= jQuery(listPager).find('li').size()) {
				maxPageButtons++
				moveIndex = (jQuery(listPager).find('li').size() - maxPageButtons)
			}
		} else if (arg_moveIndex == -1) {
			moveIndex = jQuery(listPager).find('li:visible').first().index() - 1
			moveIndex -= config.maxPageButtons
			if (moveIndex <= 0) {
				moveIndex = 0
				maxPageButtons++
			}
		}
		
		// Show relevant paging links
		jQuery(listPager).find('li').hide()
		jQuery(listPager).find('li').slice(moveIndex, moveIndex + maxPageButtons).show()
		jQuery(listPager).find('li:visible').first().find('a').click()
		
		// Hide navigation buttons if not needed
		if (jQuery(listPager).find('li').last().is(':visible') == true) {
			jQuery(listPager).find('a').last().hide()
		} else {
			jQuery(listPager).find('a').last().show()
		}

		if (jQuery(listPager).find('li').first().is(':visible') == true) {
			jQuery(listPager).find('a').first().hide()
		} else {
			jQuery(listPager).find('a').first().show()
		}
	}
	
	
	
	/* Start public */
	return {
		/**
		 * Initializes control that helps with paging through a table
		 *
		 * @param {String} selector jQuery selector
		 * @param {String} rootPath rootPath path of the url to be loaded
		 * @example
		 * workflow.alertList.Init('div.tag_mainList', '/MunicipalityName')
		 */
		Init: function(selector) {
		    var rootPath = "";
		    rootPath = jQuery('#MunicipalityName').val();
			jQuery(selector).each( function() {
				if (jQuery(this).data('listPager_initialized') != true) {
					init(jQuery(this))
				}
				jQuery(this).data('listPager_initialized', true)
			})
			config.rootPath = rootPath
		}
	}
	/* End public */
})();






/**
 * @namespace Lets a user switch between different panels
 * It fetches links to anchors and makes them show/hide buttons
 *
 * @requires jQuery
 * @example
 * var tabs = workflow.tabs.Init("ul.tabs a")
 */
workflow.tabs = function(selector) {
	var root = jQuery(selector)
	var activePanel
	
	function handleSpecialContent(tagName) {
		if (tagName.indexOf('tag_mapviewLarge') > 0) {
			// Opening Google Maps
			var xmlURL = jQuery('input.tag_mapXML').val()
			if (xmlURL != "") {
				oMap = new Estate.GoogleMaps(
					{
						mapId: 'Map',
						locationsUrl: xmlURL
					},
					"oMap"
				)
				oMap.Init()
			} else {
				throw new Error("Input field 'tag_mapXML' does not contain an URL to an XML.")
			}
		}
	}
	
	
	
	/**
	 * Initializes the tab functionality
	 *
	 * @requires jQuery
	 * @example
	 * var tabs = workflow.tabs.Init("ul.tabs a")
	 * tabs.Init()
	 */
	this.Init = function() {
		// Hide all panels except the first
		jQuery(root).each(function(index) {
			if (index == 0) {
			    jQuery(this).parent().addClass('active')
			}
			if (index > 0) {
				jQuery(jQuery(this).attr('href')).hide()
			}
		})
		
		jQuery(root).click( function(event) {
			event.stopPropagation()
			event.preventDefault()
			
			// Hide all
			jQuery(root).each(function() {
				jQuery(this).parent().removeClass('active')
				jQuery(jQuery(this).attr('href')).hide()
			})
			jQuery('#FilterPanel').hide();
			
			// Show selected
			jQuery(this).parent().addClass('active')
			activePanel = jQuery(this).attr('href')
			jQuery(activePanel).show()
			handleSpecialContent(jQuery(activePanel).attr('class'))
		})
		
		var hash =  window.location.hash;
	    if (hash && jQuery(hash).size()){ 
		    // Hide all
		    jQuery(root).each(function() {
			    jQuery(this).parent().removeClass('active')
			    jQuery(jQuery(this).attr('href')).hide()
		    })
		    jQuery('#FilterPanel').hide();
			
		    // Show selected
		    jQuery("a[href="+hash+"]").parent().addClass('active')
		    jQuery(hash).show()
		    handleSpecialContent(jQuery(hash).attr('class'))
		}
	}
};






/**
 * Sets events to ask the user if he really wants to leave the page
 *
 * @example
 * workflow.confirmLeave.Init()
 */
workflow.confirmLeave = (function() {
	function askConfirmation(event) {
		confirm('U heeft aanpassingen gemaakt die niet zijn opgeslagen. Weet u zeker dat u deze pagina wilt verlaten?')
	}
	
	

	/* START PUBLIC */
	return {
		Init: function() {
			if (document.getElementById('ShowConfirmation') && jQuery('input.js_saveList, input.js_saveList2').size() > 0) {
				// If some specific button is available...
				if (document.getElementById('ShowConfirmation').value == "true") {
					// ...and if confirmation option is on
					jQuery('div.headerContainer a').click(function(event) {
						if (jQuery('div.tag_itemStatus').not(':contains("Sent")').size() > 0 && jQuery('input.js_saveList').size() > 0 ||
							jQuery('span.js_checkboxList :checked').size() > 0 && jQuery('input.js_saveList2').size() > 0)
							{
							// Dot his if either the status of an item is changed in the "New alerts"-list
							// or an item is selected through a checkbox
							var leave = confirm('U heeft aanpassingen gemaakt die niet zijn opgeslagen. Weet u zeker dat u deze pagina wilt verlaten?')
							if (leave == false) {
								event.stopPropagation()
								event.preventDefault()
							}
						}
					})
				}
			}
		}
	}
	/* END PUBLIC */
})();







/**
 * @namespace Creates and handles events for review button in alert details box
 *
 * @requires jQuery
 */
workflow.review = (function() {
	var root
	var hideDetailsId = "HideDetails"
	var alertId = Estate.StringTools.GetQueryString("alertId")
	
	function showHideButtons() {
		if (jQuery(root).find('div.tag_choices:animated').size() == 0) {
			if (jQuery(root).find('div.tag_choices:visible').size() == 0) {
				createHider()
				jQuery(root).find('div.tag_choices').fadeIn( 600, "easeInOutCubic" )
				jQuery('#'+ hideDetailsId).fadeTo( 600, 0.75, "easeInOutCubic" )
			} else {
				createHider()
				jQuery(root).find('div.tag_choices').fadeOut( 600, "easeInOutCubic" )
				jQuery('#'+ hideDetailsId).fadeOut( 600, "easeInOutCubic" )
			}
		}
	}
	
	// Adds a div that should hide the whole page
	function createHider() {
		if (jQuery('#'+ hideDetailsId).size() == 0) {
			jQuery('body').append('<div class="divPopupBackground" id="'+ hideDetailsId +'"></div>')
			jQuery('#'+ hideDetailsId).click( function() {
				showHideButtons()
			})

		}
	}
	
	
	return {
		/**
		 * Initializes events for review button in alert details box
		 *
		 * @param {String} selector jQuery selector that selects the review container
		 * @param {String} rootPath path of the url to be loaded
		 * @requires jQuery
		 * @example
		 * workflow.review.Init("div.tag_review")
		 */
		Init: function(selector, rootPath) {
			root = jQuery(selector)
			jQuery(root).addClass('reviewActive')
			jQuery(root).find('div.tag_choices').hide()
			
			jQuery('div.containerMain').css('position', 'static')
			
			jQuery(root).find('div.tag_choices input.js_partApprove').click( function() {
				top.workflow.openFrame.Open('dialogApprove', alertId, rootPath)
			})
			
			jQuery(root).find('div.tag_choices input.js_reject').click( function() {
				top.workflow.openFrame.Open('dialogDeny', alertId, rootPath)
			})

			jQuery(root).find('div.tag_choices input.js_executed').click( function() {
				top.workflow.openFrame.Open('dialogExecuted', alertId, rootPath)
			})

			jQuery(root).find('div.tag_choices input.js_executed2').click( function() {
				top.workflow.openFrame.Open('dialogExecuted2', alertId, rootPath)
            })
        
            jQuery(root).find('div.tag_choices input.js_executed3').click(function() {
                top.workflow.openFrame.Open('dialogExecuted3', alertId, rootPath)
            })

			jQuery(root).find('div.tag_choices input.js_accept').click( function() {
				top.workflow.openFrame.Open('dialogExecuted4', alertId, rootPath)
            })
        
            jQuery(root).find('div.tag_choices input.js_decline').click(function() {
				top.workflow.openFrame.Open('dialogDecline', alertId, rootPath)
            })

			jQuery(root).find('div.tag_choices input.js_cancel').click( function() {
				showHideButtons()
			})
			
			jQuery(root).find('span.tag_reviewStatus').click( function() {
				showHideButtons()
			})
		}
	}
})();
